from rest_framework import serializers
from .models import User
from django.contrib.auth.password_validation import validate_password

class UserRegisterSerializer(serializers.ModelSerializer):
    """用户注册序列化器"""
    password = serializers.CharField(
        write_only=True,
        required=True,
        validators=[validate_password],
        style={'input_type': 'password'}
    )
    password2 = serializers.CharField(
        write_only=True,
        required=True,
        style={'input_type': 'password'}
    )
    
    class Meta:
        model = User
        fields = ['username', 'email', 'password', 'password2']
    
    def validate(self, attrs):
        """验证两次密码是否一致"""
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError({
                'password': '两次输入的密码不一致'
            })
        return attrs
    
    def create(self, validated_data):
        """创建新用户"""
        validated_data.pop('password2')
        user = User.objects.create_user(**validated_data)
        return user

class UserLoginSerializer(serializers.Serializer):
    """用户登录序列化器"""
    username = serializers.CharField(required=True)
    password = serializers.CharField(required=True, style={'input_type': 'password'})

class UserProfileSerializer(serializers.ModelSerializer):
    """用户个人信息序列化器"""
    avatar = serializers.SerializerMethodField()
    
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'avatar', 'bio', 'created_at']
        read_only_fields = ['id', 'username', 'email', 'created_at']
    
    def get_avatar(self, obj):
        """获取头像的完整URL"""
        if obj.avatar:
            return self.context['request'].build_absolute_uri(obj.avatar.url)
        return None

class UserUpdateSerializer(serializers.ModelSerializer):
    """用户信息更新序列化器"""
    avatar = serializers.ImageField(required=False)
    
    class Meta:
        model = User
        fields = ['bio', 'avatar']
    
    def update(self, instance, validated_data):
        """更新用户信息"""
        # 处理头像上传
        if 'avatar' in validated_data:
            # 如果有新头像上传，先删除旧头像
            if instance.avatar:
                instance.avatar.delete()
            instance.avatar = validated_data['avatar']
        
        # 更新其他字段
        if 'bio' in validated_data:
            instance.bio = validated_data['bio']
        
        instance.save()
        return instance